﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Data.OleDb;
using System.Diagnostics;


namespace Kwik.Orm
{
	/// <summary>
	/// Mapper class for System.Data.SqlClient connections
	/// </summary>
	public sealed class OleDbSchema: BaseSchema 
	{
		/// <summary>
		/// Create a new SqlClientMapper object
		/// </summary>
		public OleDbSchema():base("", "System.Data.OleDb") { }
		/// <summary>
		/// Create a new SqlClientMapper object with the supplied connectionstring
		/// </summary>
		/// <param name="connectionString"></param>
		public OleDbSchema(string connectionString) : base(connectionString, "System.Data.OleDb") { }

		/// <summary>
		/// Load the schema with the supplied connection
		/// </summary>
		/// <param name="conn">Connection to load the schema from</param>
		public void Load(OleDbConnection conn)
		{
			Trace.WriteLine("Kwik.Orm.OleDbMapper.Load: Loading OleDb schema");
			base.Load(conn);
			this.LoadColumns(conn);

			//detecting mssql oledb
			if (conn.Provider.ToLower().IndexOf("sqloledb") != -1 || conn.Provider.ToLower().IndexOf("sqlncli") != -1)
			{
				Trace.WriteLine("Kwik.Orm.OleDbMapper.Load: Using SqlClientMapper.LoadDescriptions");
				SqlClientSchema.LoadDescriptions(conn, this);
			}
		}

		/// <summary>
		/// Sets the connectionstring and loads the schema
		/// </summary>
		/// <param name="connectionString">Connectionstring to use to initialize a connection</param>
		public void Load(string connectionString)
		{
			this.ConnectionString = connectionString;
			this.Load();
		}

		/// <summary>
		/// Load the schema with current connectionstring
		/// </summary>
		public override void Load()
		{
			OleDbConnection conn = new OleDbConnection(this.ConnectionString);
			conn.Open();
			this.Load(conn);
			conn.Close();
			conn.Dispose();
		}

		/// <summary>
		/// Load column options
		/// </summary>
		/// <param name="conn"></param>
		private void LoadColumns(OleDbConnection conn)
		{
			DataTable table = conn.GetSchema("Columns");
			foreach (DataRow row in table.Rows)
			{
				string tableName = Convert.ToString(row["TABLE_NAME"]);
				string columnName = Convert.ToString(row["COLUMN_NAME"]);
				if (this.Tables.ContainsKey(tableName) && this.Tables[tableName].Columns.ContainsKey(columnName))
				{
					string columnDefault = Convert.ToString(row["COLUMN_DEFAULT"]);
					string columnDesc = Convert.ToString(row["DESCRIPTION"]);
					this.Tables[tableName].Columns[columnName].DefaultValue = columnDefault.TrimStart('(').TrimEnd(')');
					this.Tables[tableName].Columns[columnName].Description = columnDesc;

					Trace.WriteLine("Kwik.Orm.OleDbMapper.LoadColumns: Default value for " + tableName + "." + columnName + " is '" + this.Tables[tableName].Columns[columnName].DefaultValue + "'");
				}
			}
		}


	}
}
